import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webview_flutter/webview_flutter.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  // 全屏
  SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);
  runApp(const _App());
}

class _App extends StatelessWidget {
  const _App();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        scaffoldBackgroundColor: const Color(0xFF141414),
        canvasColor: const Color(0xFF141414),
      ),
      home: const _EulaPage(), // 首屏：协议
    );
  }
}

class _EulaPage extends StatefulWidget {
  const _EulaPage();

  @override
  State<_EulaPage> createState() => _EulaPageState();
}

class _EulaPageState extends State<_EulaPage> {
  @override
  void initState() {
    super.initState();
    _checkAgreed();
  }

  Future<void> _checkAgreed() async {
    final prefs = await SharedPreferences.getInstance();
    final agreed = prefs.getBool('eula_agreed') ?? false;

    if (agreed) {
      // 已同意 → 直接进入 WebView
      if (mounted) {
        Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (_) => const _MainWebPage()),
          (_) => false,
        );
      }
    } else {
      // 未同意 → 弹窗
      if (mounted) _showDialog();
    }
  }

  Future<void> _showDialog() async {
    final agreed = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => _EulaDialog(),
    );

    if (agreed == true) {
      final prefs = await SharedPreferences.getInstance();
      await prefs.setBool('eula_agreed', true);
      if (mounted) {
        Navigator.of(context).pushAndRemoveUntil(
          MaterialPageRoute(builder: (_) => const _MainWebPage()),
          (_) => false,
        );
      }
    } else {
      SystemNavigator.pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(body: SizedBox.expand());
  }
}

class _EulaDialog extends StatelessWidget {
  final userUrl = 'https://service-agreement.salted-fish.top';
  final privacyUrl = 'https://privacy-policy.salted-fish.top';

  @override
  Widget build(BuildContext context) {
    final style = TextStyle(
      color: Colors.blue,
      decoration: TextDecoration.underline,
    );
    return AlertDialog(
      title: const Text('用户协议与隐私政策'),
      content: SingleChildScrollView(
        child: RichText(
          text: TextSpan(
            style: TextStyle(color: Colors.black),
            children: [
              const TextSpan(text: '请您仔细阅读并同意'),
              TextSpan(
                text: '《用户协议》',
                style: style,
                recognizer:
                    TapGestureRecognizer()
                      ..onTap =
                          () => Navigator.of(context).push(
                            MaterialPageRoute(
                              builder:
                                  (_) =>
                                      _PolicyPage(title: '用户协议', url: userUrl),
                            ),
                          ),
              ),
              const TextSpan(text: '和'),
              TextSpan(
                text: '《隐私政策》',
                style: style,
                recognizer:
                    TapGestureRecognizer()
                      ..onTap =
                          () => Navigator.of(context).push(
                            MaterialPageRoute(
                              builder:
                                  (_) => _PolicyPage(
                                    title: '隐私政策',
                                    url: privacyUrl,
                                  ),
                            ),
                          ),
              ),
              const TextSpan(text: '，否则将无法继续使用本应用。'),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(false),
          child: const Text('不同意'),
        ),
        ElevatedButton(
          onPressed: () => Navigator.of(context).pop(true),
          child: const Text('同意'),
        ),
      ],
    );
  }
}

class _PolicyPage extends StatelessWidget {
  final String title;
  final String url;
  const _PolicyPage({required this.title, required this.url});

  @override
  Widget build(BuildContext context) {
    final controller =
        WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..loadRequest(Uri.parse(url));

    return Scaffold(
      appBar: AppBar(title: Text(title), centerTitle: true),
      body: WebViewWidget(controller: controller),
    );
  }
}

class _MainWebPage extends StatefulWidget {
  const _MainWebPage();

  @override
  State<_MainWebPage> createState() => _MainWebPageState();
}

class _MainWebPageState extends State<_MainWebPage> {
  DateTime? _lastTime;

  Future<bool> _onBack() async {
    final now = DateTime.now();
    if (_lastTime == null ||
        now.difference(_lastTime!) > const Duration(seconds: 2)) {
      _lastTime = now;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('再按一次退出'), duration: Duration(seconds: 2)),
      );
      return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (didPop, result) async {
        if (didPop) return;
        final allow = await _onBack();
        if (allow && mounted) SystemNavigator.pop();
      },
      child: Scaffold(body: const _SimpleWebView()),
    );
  }
}

class _SimpleWebView extends StatefulWidget {
  const _SimpleWebView();

  @override
  State<_SimpleWebView> createState() => _SimpleWebViewState();
}

class _SimpleWebViewState extends State<_SimpleWebView> {
  late final WebViewController _controller;

  @override
  void initState() {
    super.initState();
    _controller =
        WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setBackgroundColor(const Color(0xFF141414))
          ..enableZoom(false)
          ..loadFlutterAsset('assets/web/index.html');
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Stack(
      children: [
        Positioned(
          top: -1,
          left: -1,
          right: -1,
          bottom: -1,
          child: SizedBox(
            width: size.width,
            height: size.height,
            child: WebViewWidget(controller: _controller),
          ),
        ),
      ],
    );
  }
}
